<?php

namespace app\Api\controller;

use app\common\business\SGoods as SGoodsBus;
use app\common\business\SGroup as SGoodsGroupBus;
use app\common\lib\Check;
use app\common\model\mysql\SGoodsGroupBuying;
use app\common\model\mysql\SGoodsGroupLadder;
use app\common\model\mysql\SGoodsGroupPlay;
use app\common\model\mysql\SGoodsGroupUser;
use app\common\model\mysql\SGoodsImage;

class SGroup extends ApiBase
{
    // 拼团商品数据列表
    public function goodsGroupList(){
        // 获取分页参数
        $page = $this->request->param('pageNum', 1);
        $limit = $this->request->param('pageSize', 10);
        $groupName = $this->request->param('groupName',"");
        if($groupName){
            $where[] = ['a.group_name', 'like', '%'.$groupName.'%'];
        }
        $where[] = ["a.goods_status", "=", '0'];
        $where[] = ["a.action_status", "=", '0'];
        $where[] = ['a.del_flag', '=', '0'];
        try {
            $field = "a.goods_group_id,a.goods_id,a.group_name,a.start_time,a.end_time,a.time,a.success_num,a.action_status,b.selling_price,b.price,b.stock,b.quantity_sold,b.main_img_url";
            $goodsData = (new SGoodsGroupBus())->getNormalGoodsGroupData($where, $field, $limit, $page);
            // 处理图片URL
            foreach ($goodsData['data'] as &$goods) {
                $goods['main_img_url'] = (new Check())->checkUrl($goods['main_img_url']);
            }
        }catch (\Exception $e){
            $goodsData = [];
        }
        return show(config("status.success"),"拼团商品数据列表",$goodsData);
    }

    // 拼团人数及头像
    public function groupSuccess(){
        $limit = $this->request->param('limit', 3);
        $where[] = ["status", "=", "1"];
        $groupCount = (new SGoodsGroupBuying())->getNormalGoodsGroupBuyingCount($where);
        $groupBuyingIds = (new SGoodsGroupBuying())->getNormalGoodsGroupBuyingIds($where);
        // 检查$groupBuyingIds数组的大小
        if (count($groupBuyingIds) > 5) {
            // 计算要随机选择的元素数量（数组大小的一半，取整）
            $halfSize = (int)ceil(count($groupBuyingIds) / 2);
            // 从$groupBuyingIds中随机选择一半的键名
            $randomKeys = array_rand($groupBuyingIds, $halfSize);
            // 使用这些键名来获取对应的值，组成新的$groupBuyingIds数组（或子集）
            $randomGroupBuyingIds = array_map(function($key) use ($groupBuyingIds) {
                return $groupBuyingIds[$key];
            }, $randomKeys);
            $map[] = ["group_buying_id", "in", $randomGroupBuyingIds];
        } else {
            // 如果$groupBuyingIds数组大小不超过5，则直接使用它
            $map[] = ["group_buying_id", "in", $groupBuyingIds];
        }
        $groupUserData = (new SGoodsGroupUser())->getGroupUserLimitList($map,"uid,avatar",$limit);
        $data = [
            'groupCount'=>$groupCount,
            'groupUserData'=>$groupUserData,
        ];
        return show(config("status.success"),"拼团人数及头像",$data);
    }

    // 拼团商品详情
    public function goodsGroupDetails(){
        $goods_group_id = $this->request->param("goods_group_id","","trim");
        if(empty($goods_group_id)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $goodsField = "goods_group_id,goods_id,group_name,group_desc,start_time,end_time,time,is_restrict,pay_count,once_pay_count,gather_status,action_status,logistics_mode";
            $goodsGroupData = (new SGoodsGroupBus)->getGoodsGroupById($goods_group_id,$goodsField);
            if($goodsGroupData){
                $goodsGroupData['logistics_mode'] = explode(',',$goodsGroupData['logistics_mode']);
                $goodsGroupData['group_price'] = number_format((new SGoodsGroupLadder())->getGroupLadderMinPrice($goods_group_id), 2, '.', '');
                $goodsGroupData['setGroupDataList'] = (new SGoodsGroupLadder())->getGroupLadder($goods_group_id);
                $goodsGroupData['goodsData'] = (new SGoodsBus)->getGoodsById($goodsGroupData['goods_id'],'goods_id,main_img_url,goods_name,selling_price,stock,status,price,goods_details,quantity_sold,sales,old_goods_id');
                $goodsGroupData['goodsData']['quantity_sold'] = $goodsGroupData['goodsData']['quantity_sold']+$goodsGroupData['goodsData']['sales'];
                unset($goodsGroupData['goodsData']['sales']);
                $getImagesArr = (new SGoodsImage())->getImages($goodsGroupData['goods_id']);
                $goodsGroupData['goodsData']['goods_img'] = $getImagesArr;
                //原始商品
                $goodsGroupData['oldGoodsData'] = (new SGoodsBus)->getGoodsById($goodsGroupData['goodsData']['old_goods_id'],'goods_id,selling_price,stock,status,del_flag');
                //即将成团数据
                $map[] = ['a.goods_group_id','=',$goods_group_id];
                $map[] = ['a.status','=','0'];
                $map[] = ['a.del_flag','=','0'];
                $map[] = ['b.is_initiator','=','0'];
                $goodsGroupData['groupBuyingData'] = (new SGoodsGroupBuying())->getNormalGoodsGroupBuying($map,"a.group_buying_id,a.buying_count_num,a.yet_buying_num,b.uid,b.nickname,b.avatar");
            }
        }catch (\Exception $e){
            $goodsGroupData = [];
        }
        return show(config("status.success"),"拼团商品详情",$goodsGroupData);
    }

    //拼团玩法详情
    public function goodsGroupPlayDetails(){
        try {
            $groupUserData = (new SGoodsGroupPlay())->getGoodsGroupPlayByIdFind(1,"goods_group_play_id,goods_group_play_details");
        }catch (\Exception $e){
            $groupUserData = [];
        }
        return show(config("status.success"),"拼团玩法详情",$groupUserData);
    }
}
